package cn.kgc.ossdemo.controller;

import cn.kgc.ossdemo.util.AliyunOSSUtil;
import com.sun.javafx.iio.ios.IosDescriptor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;

@Controller
public class ossController {

    private InputStream inputStream;

    @RequestMapping("/toupload")
    public String toupload(){
        return "upload";
    }
    @RequestMapping("/upload")
    public String upload(@RequestParam("projectheadpic")MultipartFile projectheadpic, Model model){
        if (projectheadpic!=null){
            String filename=projectheadpic.getOriginalFilename();
            inputStream = null;
            try{
                inputStream =projectheadpic.getInputStream();
            }catch (IOException e){
                e.printStackTrace();
            }
            try{
                String upload= AliyunOSSUtil.upload(inputStream,filename);
                model.addAttribute("imgURL","https://distribution-crowd-parent.oss-cn-beijing.aliyuncs.com/"+upload);
                System.out.println("https://distribution-crowd-parent.oss-cn-beijing.aliyuncs.com/"+upload);
                model.addAttribute("msg","文件上传成功");
                return "upload";
            }catch (Exception e){
                e.printStackTrace();
                model.addAttribute("msg",e.getMessage());
                return "upload";
            }
        }else {
            model.addAttribute("msg","请选择文件");
            return "upload";
        }
    }
}
